const Model = require('./index')

class ArticleModel extends Model {
  /**
   * 分页查询文章列表
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} conditions
   * @returns
   */
  async findPage ({ pageNo, pageSize, andConditions, orConditions }) {
    const andSql = this.generateWhereClause(andConditions)
    const completeSql = this.generateWhereClauseOR(orConditions, andSql)
    const sql = `select arc.*, user.nickname from article arc
      left join user on user.id = arc.userId ${completeSql} 
      order by arc.createTime desc
      limit ${pageSize} offset ${(pageNo - 1) * pageSize}`
    try {
      const list = await this.db.query(sql)
      const total = await this.total(completeSql)
      return {
        list,
        total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 获取文章总数量
   * @param {*} conditionSql
   * @returns
   */
  async total (conditionSql) {
    const sql = `select count(*) as total from article arc 
    left join user on user.id = arc.userId ${conditionSql}`
    try {
      const total = await this.db.query(sql)
      return total[0].total
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 根据文章id删除文章，同时删除与文章相关的点赞、收藏、动态、评论
   * @param {*} articleId
   */
  async delete (articleId) {
    const sql = `delete article, article_comment, user_collect_article, user_agree_article, user_agree_comment, dynamics from article 
      left join article_comment on article_comment.articleId = article.id
      left join user_collect_article on user_collect_article.articleId = article.id
      left join user_agree_article on user_agree_article.articleId = article.id
      left join user_agree_comment on user_agree_comment.commentId = article_comment.id
      left join dynamics on dynamics.articleId = article.id
      where article.id = ?`
    try {
      await this.db.query(sql, [articleId])
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 更新文章status状态
   * @param {*} articleId
   * @param {*} status
   */
  async updateStatus (articleId, status) {
    const sql = 'update article set status = ? where id = ?'
    try {
      await this.db.query(sql, [status, articleId])
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new ArticleModel('article')
